package com.kensure.shike.weixin.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import co.kensure.frame.Const;
import co.kensure.frame.JSBaseService;
import co.kensure.http.HttpUtils;
import co.kensure.io.FileUtils;
import co.kensure.mem.QRUtils;
import co.kensure.mem.Utils;
import co.kensure.weixin.WXUtils;

import com.alibaba.fastjson.JSONObject;
import com.kensure.mycom.config.service.MyConfigService;
import com.kensure.shike.constant.BusiConstant;
import com.kensure.shike.user.model.SKUser;
import com.kensure.shike.user.service.SKUserService;

/**
 * 微信小程序,登录接口
 * 
 * @author fankd created on 2018-5-8
 * @since
 */
@Service
public class WeixinXiaoChengXuService extends JSBaseService {
	@Resource
	SKUserService sKUserService;
	@Resource
	WeixinSignService weixinSignService;

	/**
	 * 微信用户登录类
	 * 
	 * @param parameters
	 * @return
	 */
	public String weixinLogin(String code, String nickname, String topImg, Long refereeId) {
		JSONObject json = getWeixinOpenid(code);
		String session_key = json.getString("session_key");
		String openid = json.getString("openid");
		String token = sKUserService.addAndLogin(openid, session_key, nickname, topImg, refereeId);
		return token;
	}

	private JSONObject getWeixinOpenid(String code) {
		String appid = MyConfigService.getMyConfig("weixin_appid").getVal();
		String appsecret = MyConfigService.getMyConfig("weixin_appsecret").getVal();
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
		String content = HttpUtils.getBody(url);
		JSONObject json = JSONObject.parseObject(content);
		System.out.println("content==" + content);
		return json;
	}

	/**
	 * 微信用户绑定手机
	 * 
	 * @return
	 */
	public void weixinUpdatePhone(String code, String encryptedData, String iv) {
		JSONObject codejson = getWeixinOpenid(code);
		String session_key = codejson.getString("session_key");
		String openid = codejson.getString("openid");
		SKUser user = sKUserService.selectByOpenid(openid);
		user.setSessionKey(session_key);
		sKUserService.update(user);
		JSONObject json = WXUtils.getUserInfo(encryptedData, user.getSessionKey(), iv);
		String phoneNumber = json.getString("phoneNumber");
		sKUserService.updatePhone(user.getId(), phoneNumber);
	}

	/**
	 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-
	 * code/wxacode.getUnlimited.html
	 * 获取小程序码，适用于需要的码数量极多的业务场景。通过该接口生成的小程序码，永久有效，数量暂无限制。 更多用法详见 获取二维码
	 * 
	 * @return
	 */
	public String getUnlimited(String scene, String page) {
		String temp = Utils.getUUID();
		String path = "/qrcode/fx/" + temp + ".png";
		FileUtils.createDir(Const.ROOT_PATH+"/qrcode/fx/");
		String result = genCode(scene, page, path);
		return result;
	}

	/**
	 * 生成我的二维码
	 * 
	 * @return
	 */
	public String genMyCode(long userid) {
		// 二维码图片
		String path = "/qrcode/user/" + userid + ".png";
		String fold = Const.ROOT_PATH+"/qrcode/user/";
		FileUtils.createDir(fold);
		File file = new File(Const.ROOT_PATH+path);
		if(!file.exists()){
			genCode("" + userid, "pages/index/index", path);
		}
		return path;
	}

	/**
	 * 生成微信二维码
	 * 
	 * @return
	 */
	private String genCode(String scene, String page, String path) {
		// 二维码图片
		String ACCESS_TOKEN = weixinSignService.getToken();
		String result = null;
		try {
			URL getCodeUrl = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + ACCESS_TOKEN);
			HttpURLConnection httpURLConnection = (HttpURLConnection) getCodeUrl.openConnection();
			httpURLConnection.setRequestMethod("POST");// 提交模式
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			JSONObject paramJson = new JSONObject();
			paramJson.put("scene", scene);
			paramJson.put("page", page);
			paramJson.put("is_hyaline", true);
			printWriter.write(paramJson.toJSONString());
			printWriter.flush();
			BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
			OutputStream ost = new FileOutputStream(new File(Const.ROOT_PATH + path));
			int len;
			byte[] arr = new byte[1024];
			while ((len = bis.read(arr)) != -1) {
				ost.write(arr, 0, len);
				ost.flush();
			}
			ost.close();
			result = BusiConstant.getHttpsFullUrl(path);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 订单二维码，和小程序其实没有多大关联
	 */
	public static String genOrderUrl(Long orderid) {
		String url = BusiConstant.getHttpsFullUrl("/wv/queren?id=" + orderid);
		String path = "/qrcode/order/" + orderid + ".png";
		FileUtils.createDir(Const.ROOT_PATH+"/qrcode/order/");
		QRUtils.genQR(300, 300, url, Const.ROOT_PATH + path);
		return BusiConstant.getHttpsFullUrl(path);
	}
}
